<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeName"
        />
        <!-- 树形组件
         :expand-on-click-node="false" 禁用点击节点折叠或展开
        default-expand-all 展开所有的节点
        highlight-current 设置选中节点的高亮
        -->
        <!-- node-key="id"如果想要通过key方式选中某个或多个节点，需要在el-tree添加 node-key="id" -->
        <!-- @node-click:节点点击的时间 -->
        <el-tree
          ref="tree"
          node-key="id"
          highlight-current
          default-expand-all
          :expand-on-click-node="false"
          :data="list"
          :props="{label:'name'}"
          @node-click="nodeClick"
        />

      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-allow="'add'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-allow="'import_excel'" size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button v-allow="'export_excel'" size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableList">
          <el-table-column align="center" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>未知</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />

          <el-table-column align="center" label="操作">
            <template #default="{row}">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button
                type="text"
                size="mini"
                @click="assignRole(row.id)"
              >角色</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @confirm="confirmDel(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" type="text" size="mini">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" style="height:40px">
          <el-pagination
            :current-page="queryParams.page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="queryParams.pagesize"
            layout="total, prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>

      </div>
      <!-- excel批量导入的组件
      :变量名.sync="showExcelDialog"可以和一个子组件进行双向数据的绑定 语法糖

      :aa="showExcelDialog"
      @update:showExcelDialog = "showExcelDialog=$event"

       -->
      <importExcel
        :show-excel-dialog.sync="showExcelDialog"
        @success="initDeptEmployee"
      />

      <!-- 给员工分配角色的弹层 -->
      <el-dialog title="分配角色" :visible.sync="showRoleDialog">
        <el-checkbox-group v-model="roleIds">
          <el-checkbox
            v-for="item in roleList"
            :key="item.id"
            :label="item.id"
          >{{ item.name }} </el-checkbox>

        </el-checkbox-group>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="submit"> 确定</el-button>
            <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getDepartments } from '@/api/department'
import { getDptEmployee, exportEmployee, delEmployee, getEmployeeDetail,
  assignUserRoles } from '@/api/employee'
import { getEnabledRoles } from '@/api/role'
import { transListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import importExcel from './components/import_excel.vue'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      currentId: null,
      roleList: [],
      roleIds: [], // 保存的使用已经选择的checkbox的id
      showRoleDialog: false, // 分配角色的弹层
      showExcelDialog: false,
      tableList: [],
      list: [],
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 10,
        keyword: '' // 模糊搜索字段
      },
      total: 0
    }
  },
  created() {
    this.initDepartment()
  },
  methods: {
    async  submit() {
      await assignUserRoles({ id: this.currentId, roleIds: this.roleIds })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    },
    // 分配角色
    async assignRole(id) {
      this.currentId = id
      // 保证所有的数据加载完毕，再执行后续的代码
      await this.initEnabledRoles()
      this.showRoleDialog = true
    },
    // 获取可用的角色列表
    async initEnabledRoles() {
      this.roleList = await getEnabledRoles()
      // 获取当前用户已经拥有的角色的id
      const { roleIds } = await getEmployeeDetail(this.currentId)
      // 让用户拥有相应的角色的id的checkbox处于选中状态
      this.roleIds = roleIds
    },
    // 实现删除功能
    async confirmDel(id) {
      await delEmployee(id)
      if (this.tableList.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.initDeptEmployee()
    },
    async exportEmployee() {
      const result = await exportEmployee()
      // result 返回的是一个Blob对象
      // FileSaver.saveAs(Blob对象, '文件名称')
      FileSaver.saveAs(result, '黑马员工表')
    },
    changeName() {
      console.log(this.queryParams.keyword)
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // 将页码改1
        this.queryParams.page = 1
        // 发送请求实现数据获取
        this.initDeptEmployee()
      }, 300)
    },
    handleCurrentChange(val) {
      this.queryParams.page = val
      this.initDeptEmployee()
    },
    // 获取部门对应的员工
    async initDeptEmployee() {
      // 获取当前部门id对相应的部门数据
      const result = await getDptEmployee(this.queryParams)
      this.tableList = result.rows
      this.total = result.total
    },
    async  nodeClick(data) {
      console.log(data, 'data')
      // 将当前部门的id保存到 queryParams.departmentId中
      this.queryParams.departmentId = data.id
      // 获取当前部门id对相应的部门数据
      this.initDeptEmployee()
    },
    async initDepartment() {
      this.list = transListToTreeData(await getDepartments(), 0)
      this.queryParams.departmentId = this.list[0].id
      // 让当前传入的部门id对象的节点处于选中的状态  this.queryParams.departmentId
      // 保证dom更新完成，再设置 this.$nextTick
      // console.log(this.queryParams.departmentId)
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.queryParams.departmentId)
      })
      this.initDeptEmployee()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
